package za.ac.wits.elen7045.persistence.datasource.sqlite;

import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import za.ac.wits.elen7045.persistence.Environment;
import za.ac.wits.elen7045.persistence.PersistentObject;
import za.ac.wits.elen7045.persistence.datasource.SQLDataSource;
import za.ac.wits.elen7045.persistence.exception.DataSourceConnectionException;
import za.ac.wits.elen7045.persistence.util.SystemUtilities;

public abstract class SQLiteDataSource<T extends PersistentObject> extends SQLDataSource<T> {

	protected static Connection connection;
	protected ResultSet resultSet;
	
	protected File getSourceFile() {
		String database = getEnvironment() != null ? getEnvironment().getDatabase() : Environment.PRODUCTION.getDatabase();
		return new File(SystemUtilities.WORK_DIR, database);
	}
	
	@Override
	protected synchronized Connection getConnection() throws SQLException {
		if (connection == null || connection.isClosed()) {
			connection = createConnection();
		}
		return connection;
	}
	
	@Override
	protected ResultSet getResultSet() {
		return resultSet;
	}

	@Override
	protected void setResultSet(ResultSet resultSet) {
		this.resultSet = resultSet;
	}

	private Connection createConnection() throws SQLException {
		try {
			Class.forName("org.sqlite.JDBC");
			return DriverManager.getConnection("jdbc:sqlite:"+ getSourceFile().getAbsolutePath());
		} catch (ClassNotFoundException e) {
			throw new DataSourceConnectionException("Unable to load JDBC driver. Please ensure that the driver " +
													"is in the project's classpath.", e);
		}
	}
	
	/* Utilities */
	
	protected String prepareQuery(String query) {
		return query.trim().replace("  ", " ");
	}
	
}
